<template>
  <div class="note-container">
    <!-- 顶部工具栏 -->
    <div class="note-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="createNote">
          <el-icon><Plus /></el-icon>
          新建笔记
        </el-button>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索笔记..."
          style="width: 300px; margin-left: 16px;"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>
      <div class="toolbar-right">
        <el-button-group>
          <el-button :type="viewMode === 'grid' ? 'primary' : 'default'" @click="viewMode = 'grid'">
            <el-icon><Grid /></el-icon>
          </el-button>
          <el-button :type="viewMode === 'list' ? 'primary' : 'default'" @click="viewMode = 'list'">
            <el-icon><List /></el-icon>
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 分类筛选 -->
    <div class="category-filter">
      <el-button 
        v-for="category in categories"
        :key="category.id"
        :type="selectedCategory === category.id ? 'primary' : 'default'"
        @click="selectCategory(category.id)"
        size="small"
      >
        {{ category.name }}
      </el-button>
    </div>

    <!-- 笔记列表 -->
    <div class="note-list" :class="{ 'grid-view': viewMode === 'grid', 'list-view': viewMode === 'list' }">
      <div 
        v-for="note in notes"
        :key="note.id"
        class="note-card"
        @click="openNote(note)"
      >
        <div class="note-header">
          <h3 class="note-title">{{ note.title || '无标题' }}</h3>
          <el-dropdown @command="(command) => handleCommand(command, note)">
            <el-button type="text" size="small">
              <el-icon><MoreFilled /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="share">分享</el-dropdown-item>
                <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="note-content">
          <p>{{ note.summary || note.content?.substring(0, 100) + '...' }}</p>
        </div>
        <div class="note-meta">
          <div class="meta-left">
            <span class="category">{{ note.categoryName }}</span>
            <div class="tags">
              <el-tag 
                v-for="tag in note.tags?.slice(0, 3)"
                :key="tag"
                size="small"
                type="info"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
          <div class="meta-right">
            <span class="update-time">{{ formatTime(note.updateTime) }}</span>
            <el-icon v-if="note.isShared" color="#67c23a"><Share /></el-icon>
            <el-icon v-if="note.isFavorite" color="#f56c6c"><Star /></el-icon>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more">
      <el-button @click="loadMore" :loading="loading">加载更多</el-button>
    </div>

    <!-- 我的收藏 -->
    <div class="favorite-notes">
      <el-card>
        <template #header>
          <span>我的收藏</span>
        </template>
        <div class="favorite-list">
          <div 
            v-for="note in favoriteNotes"
            :key="note.id"
            class="favorite-item"
            @click="openNote(note)"
          >
            <h4>{{ note.title }}</h4>
            <p>{{ formatTime(note.updateTime) }}</p>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  getNoteList, 
  getNoteCategories, 
  searchNotes,
  deleteNote,
  getFavoriteNotes
} from '@/api/note'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const selectedCategory = ref(null)
const viewMode = ref('grid')
const categories = ref([{ id: null, name: '全部' }])
const notes = ref([])
const favoriteNotes = ref([])
const loading = ref(false)
const hasMore = ref(true)

// 分页参数
const pagination = reactive({
  page: 1,
  size: 20
})

// 获取笔记分类
const getCategories = async () => {
  try {
    const response = await getNoteCategories()
    if (response.code === 200) {
      categories.value = [{ id: null, name: '全部' }, ...response.data]
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 获取笔记列表
const getNotes = async (reset = false) => {
  if (loading.value) return
  
  loading.value = true
  try {
    const params = {
      page: reset ? 1 : pagination.page,
      size: pagination.size,
      categoryId: selectedCategory.value
    }
    
    const response = await getNoteList(params)
    if (response.code === 200) {
      const newNotes = response.data.records || []
      if (reset) {
        notes.value = newNotes
        pagination.page = 1
      } else {
        notes.value.push(...newNotes)
      }
      
      hasMore.value = newNotes.length === pagination.size
      if (!reset) {
        pagination.page++
      }
    }
  } catch (error) {
    console.error('获取笔记列表失败:', error)
    ElMessage.error('获取笔记列表失败')
  } finally {
    loading.value = false
  }
}

// 获取收藏笔记
const loadFavoriteNotes = async () => {
  try {
    const response = await getFavoriteNotes({ page: 1, size: 5 })
    if (response.code === 200) {
      favoriteNotes.value = response.data.records || []
    }
  } catch (error) {
    console.error('获取收藏笔记失败:', error)
  }
}

// 搜索笔记
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    getNotes(true)
    return
  }
  
  loading.value = true
  try {
    const response = await searchNotes(searchKeyword.value, {
      page: 1,
      size: pagination.size
    })
    if (response.code === 200) {
      notes.value = response.data.records || []
      hasMore.value = false
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 选择分类
const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId
  searchKeyword.value = ''
  getNotes(true)
}

// 加载更多
const loadMore = () => {
  getNotes()
}

// 创建笔记
const createNote = () => {
  router.push('/note/create')
}

// 打开笔记
const openNote = (note) => {
  router.push(`/note/${note.id}`)
}

// 处理命令
const handleCommand = (command, note) => {
  switch (command) {
    case 'edit':
      router.push(`/note/${note.id}/edit`)
      break
    case 'share':
      handleShare(note)
      break
    case 'delete':
      handleDelete(note)
      break
  }
}

// 分享笔记
const handleShare = (note) => {
  ElMessage.info('分享功能开发中...')
}

// 删除笔记
const handleDelete = (note) => {
  ElMessageBox.confirm(`确认要删除笔记"${note.title}"吗？`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteNote(note.id)
      ElMessage.success('删除成功')
      getNotes(true)
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleDateString()
}

// 页面加载
onMounted(() => {
  getCategories()
  getNotes(true)
  loadFavoriteNotes()
})
</script>

<style lang="scss" scoped>
.note-container {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 20px;
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.note-toolbar {
  grid-column: 1 / -1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  
  .toolbar-left {
    display: flex;
    align-items: center;
  }
}

.category-filter {
  grid-column: 1 / -1;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.note-list {
  &.grid-view {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;
  }
  
  &.list-view {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
}

.note-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  }
  
  .note-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
    
    .note-title {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      flex: 1;
    }
  }
  
  .note-content {
    margin-bottom: 12px;
    
    p {
      margin: 0;
      color: #666;
      line-height: 1.5;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
    }
  }
  
  .note-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: #999;
    
    .meta-left {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .category {
        background: #f0f0f0;
        padding: 2px 6px;
        border-radius: 4px;
      }
      
      .tags {
        display: flex;
        gap: 4px;
      }
    }
    
    .meta-right {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}

.favorite-notes {
  .favorite-list {
    .favorite-item {
      padding: 8px 0;
      cursor: pointer;
      border-bottom: 1px solid #f0f0f0;
      
      &:hover {
        background: #f8f9fa;
      }
      
      &:last-child {
        border-bottom: none;
      }
      
      h4 {
        margin: 0 0 4px 0;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      p {
        margin: 0;
        font-size: 12px;
        color: #666;
      }
    }
  }
}

.load-more {
  grid-column: 1;
  text-align: center;
  margin: 20px 0;
}

@media (max-width: 768px) {
  .note-container {
    grid-template-columns: 1fr;
    padding: 12px;
  }
  
  .note-list.grid-view {
    grid-template-columns: 1fr;
  }
}
</style>
